package com.fintech.pangu.zuul.route.tag.filter;

import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;
import com.netflix.zuul.ZuulFilter;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;

/**
 * 负责初始化HystrixRequestContext、GrayRequestContext的前置过滤器
 */
public class GrayPreZuulFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return -2;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 初始化HystrixRequestContext（new HystrixRequestContext()，并放入threadlocal）
     * 否则在使用HystrixRequestVariableDefault时报错
     */
    private void initHystrixRequestContext() {
        if (!HystrixRequestContext.isCurrentThreadInitialized()) {
            HystrixRequestContext.initializeContext();
        }
    }

    /**
     * 初始化GrayRequestContext
     * 在HystrixRequestContext.state中初始化 HystrixRequestVariableDefault : new GrayRequestContext()
     */
    private void initCurrentRequestContext(){
        GrayRequestContext.initCurrentRequestContext();
    }

    @Override
    public Object run() {
        // 初始化HystrixRequestContext
        initHystrixRequestContext();

        // 初始化GrayRequestContext
        initCurrentRequestContext();

        return null;
    }

}
